package com.inossem.warehousestorage_inossem.adapter.outStorage;

import android.app.Dialog;
import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.inossem.utils.base.ArithUtils;
import com.inossem.utils.base.RegexUtils;
import com.inossem.utils.base.Utils;
import com.inossem.utils.listener.NoDoubleClickListener;
import com.inossem.warehousestorage_inossem.R;
import com.inossem.warehousestorage_inossem.bean.outStorage.BatchBean;
import com.inossem.warehousestorage_inossem.bean.outStorage.OutStorageOtherBean;
import com.inossem.warehousestorage_inossem.bean.outStorage.OutStorageOtherOverviewBean;
import com.inossem.warehousestorage_inossem.constant.TypeEnum;
import com.inossem.warehousestorage_inossem.dialog.DialogUtils;
import com.inossem.warehousestorage_inossem.listener.GsonBeanListener;
import com.inossem.warehousestorage_inossem.listener.OutStorageDetailListener;
import com.inossem.warehousestorage_inossem.request.outStorage.AddBatchRequest;
import com.inossem.warehousestorage_inossem.utils.OutStorageUtils;

import java.util.ArrayList;
import java.util.List;

import static com.inossem.warehousestorage_inossem.R.id.batchNumber;

/**
 * 作者：wsy on 2017/12/7 16:04
 * <p>
 * 邮箱：445979770@qq.com
 */

public class OtherOutStorageDetailListAdapter extends BaseAdapter {
    public static final String CONFIRM = "1";

    private static final String FOCUS_BATCH = "1";

    private Context mContext;
    private LayoutInflater inflater;
    private OutStorageDetailListener mOutStorageOutDetailListener;
    private List<BatchBean.BatchInfoBean> mBatchList;
    private String mIsFocusBatch, mBatchNumber, mMaterielCode, mMaterielId, mFactoryId, mInventoryAddressId, mMaterielDescription, mUnit, mCanSendNumber, mActualSendNumber, mInventoryAddress, mInventoryAddressCode, specialInventory, mRetainDecimal;
    private EditText batchNumberEditText;
    private TextView actualSendNumber;
    private OutStorageOtherBean mOutStorageOtherBean;

    public List<BatchBean.BatchInfoBean> getmBatchList() {
        return mBatchList;
    }

    public String getmActualSendNumber() {
        return mActualSendNumber;
    }

    public OtherOutStorageDetailListAdapter(Context context, OutStorageOtherBean outStorageOtherBean, OutStorageOtherOverviewBean.BodyBean materielDetail, List<BatchBean.BatchInfoBean> batchList, String batchNumber,OutStorageDetailListener outStorageOtherDetailListener) {
        mContext = context;
        mBatchList = batchList == null ? new ArrayList<>() : batchList;
        mIsFocusBatch = materielDetail.getIs_focus_batch();
        mBatchNumber = batchNumber;
//        mSerial = materielDetail.getSerial();
        mMaterielId = materielDetail.getMat_id();
        mMaterielCode = materielDetail.getMat_code();
        mMaterielDescription = materielDetail.getMat_name();
        mUnit = materielDetail.getUnit_name();
        mRetainDecimal = materielDetail.getDecimal_place();
        mCanSendNumber = materielDetail.getQty();
        mOutStorageOtherBean = outStorageOtherBean;
        specialInventory = mOutStorageOtherBean.getSpecialInventory();
        mInventoryAddressCode = outStorageOtherBean.getInventoryAddressCode();
        mInventoryAddress = mInventoryAddressCode + " - " + outStorageOtherBean.getInventoryAddressValue();
        mFactoryId = materielDetail.getFty_id();
        mInventoryAddressId = materielDetail.getLocation_id();
        mOutStorageOutDetailListener = outStorageOtherDetailListener;
        inflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return mBatchList.size() + 1;
    }

    @Override
    public Object getItem(int position) {
        return mBatchList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (position == 0) {
            convertView = inflater.inflate(R.layout.view_out_storage_picking_detail_first_item, null);
            TextView serialNumber = (TextView) convertView.findViewById(R.id.serialNumber);
            TextView materielCode = (TextView) convertView.findViewById(R.id.materielCode);
            TextView materielDescription = (TextView) convertView.findViewById(R.id.materielDescription);
            TextView canSendNumber = (TextView) convertView.findViewById(R.id.canSendNumber);
            TextView calculator = (TextView) convertView.findViewById(R.id.calculator);
            actualSendNumber = (TextView) convertView.findViewById(R.id.actualSendNumber);
            TextView inventoryAddress = (TextView) convertView.findViewById(R.id.inventoryAddress);
            batchNumberEditText = (EditText) convertView.findViewById(batchNumber);
            ImageView search = (ImageView) convertView.findViewById(R.id.search);
            Button defaultBatch = (Button) convertView.findViewById(R.id.defaultBatch);
            Button addBatch = (Button) convertView.findViewById(R.id.addBatch);
//            serialNumber.setText(mSerial);
            materielCode.setText(mMaterielCode);
            materielDescription.setText(mMaterielDescription);
            canSendNumber.setText(mCanSendNumber + mUnit);
            mActualSendNumber = calculatedTotal();
            actualSendNumber.setText("".equals(mActualSendNumber) ? "" : (mActualSendNumber + mUnit));
            inventoryAddress.setText(mInventoryAddress);
            batchNumberEditText.setText(mBatchNumber);
//            batchNumber.addTextChangedListener(new QRCodeEditTextWatcher(batchNumber) {
//                @Override
//                public void onScan(String text) {
//                    Utils.closeSoftKeyboard(mContext, batchNumber);
//                    addBatchRequest(mContext, true, text, null);
//                }
//            });
            addBatch.setOnClickListener(new NoDoubleClickListener() {
                @Override
                public void onNoDoubleClick(View v) {
                    if (FOCUS_BATCH.equals(mIsFocusBatch)) {
                        Utils.middleToast(mContext, mContext.getResources().getString(R.string.activity_out_storage_allocating_detail_mandatory_batches_cannot_be_added_to_the_batch_information));
                    } else {
                        mOutStorageOutDetailListener.selectItem(0);
                        batchNumberEditText.requestFocus();
                    }
                }
            });
            defaultBatch.setOnClickListener(new NoDoubleClickListener() {
                @Override
                public void onNoDoubleClick(View v) {
                    DialogUtils.getPickingOutStorageNumberDialog(mContext, mContext.getResources().getString(R.string.activity_out_storage_allocating_detail_please_enter_the_number_of_recommended_batches), Double.parseDouble(mCanSendNumber), new DialogUtils.EditTextDialogListener() {
                        @Override
                        public void onConfirm(Dialog dialog, String result) {
                            if ("".equals(result)) {
                                Utils.middleToast(mContext, mContext.getResources().getString(R.string.activity_out_storage_allocating_detail_the_number_of_approved_batches_should_not_be_considered_empty));
                            } else if (!RegexUtils.checkDecimal(result)) {
                                Utils.middleToast(mContext, mContext.getResources().getString(R.string.activity_out_storage_allocating_detail_the_number_of_approved_batches_does_not_comply_with_the_specification));
                            } else if (!TextUtils.isEmpty(result) && !Utils.checkRetainDecimal(result, mRetainDecimal)) {
                                Utils.middleToast(mContext, String.format(mContext.getResources().getString(R.string.common_retain_decimal_illegal), TextUtils.isEmpty(mRetainDecimal) ? mContext.getResources().getString(R.string.common_retain_decimal_unlimited) : mRetainDecimal));
//                                return String.format(mContext.getResources().getString(R.string.common_retain_decimal_illegal), TextUtils.isEmpty(mRetainDecimal) ? context.getResources().getString(R.string.common_retain_decimal_unlimited) : mRetainDecimal);
                            } else if (RegexUtils.checkZero(result)) {
                                Utils.middleToast(mContext, mContext.getResources().getString(R.string.activity_out_storage_allocating_detail_the_number_of_approved_batches_recommended_must_be_greater_than_zero));
                            } else {
                                mOutStorageOutDetailListener.getDefaultBatch(result);
                                dialog.cancel();
                            }
                        }
                    }).show();
                }
            });
            search.setOnClickListener(new NoDoubleClickListener() {
                @Override
                public void onNoDoubleClick(View v) {
                    Utils.closeSoftKeyboard(mContext, search);
                    addBatchRequest(mContext, false, null, batchNumberEditText.getText().toString());
                }
            });
            calculator.setOnClickListener(new NoDoubleClickListener() {
                @Override
                public void onNoDoubleClick(View v) {
                    mOutStorageOutDetailListener.calculator();
                }
            });
        } else {
            BatchBean.BatchInfoBean pickingOutStorageItem = mBatchList.get(position - 1);
            convertView = inflater.inflate(R.layout.view_out_storage_picking_detail, null);
            TextView positionTextView = (TextView) convertView.findViewById(R.id.position);
            TextView inventoryNumber = (TextView) convertView.findViewById(R.id.inventoryNumber);
            TextView batch = (TextView) convertView.findViewById(R.id.batch);
            EditText outStorageNumber = (EditText) convertView.findViewById(R.id.outStorageNumber);
            TextView unit = (TextView) convertView.findViewById(R.id.unit);
            TextView status = (TextView) convertView.findViewById(R.id.status);
            String unitStr = pickingOutStorageItem.getUnit_name();
            positionTextView.setText(pickingOutStorageItem.getPosition_code());
//            inStorageDate.setText(pickingOutStorageItem.getInStorageDate());
            inventoryNumber.setText(pickingOutStorageItem.getStock_qty() + unitStr);
            batch.setText(pickingOutStorageItem.getBatch());
            outStorageNumber.setText(pickingOutStorageItem.getQty());
            unit.setText(unitStr);
            if (pickingOutStorageItem.getIsConfirm() != null) {
                status.setText(mContext.getResources().getString(R.string.activity_out_storage_sale_detail_status_ok));
                status.setOnClickListener(null);
            } else {
                status.setText(mContext.getResources().getString(R.string.activity_out_storage_sale_detail_click_sweep_code_to_confirm));
                status.setOnClickListener(new NoDoubleClickListener() {
                    @Override
                    public void onNoDoubleClick(View v) {
//                        mOutStorageSaleDetailListener.selectItem(0);
//                        batchNumberEditText.requestFocus();
                        /*暂时修改由于伊泰还没有具体仓位码*/
                        int index = OutStorageUtils.checkPosition(mBatchList, positionTextView.getText().toString());
                        if (index != -1) {
                            notifyDataSetChanged();
                            mOutStorageOutDetailListener.selectItem(index);
                        }
                    }
                });
            }
            outStorageNumber.setOnFocusChangeListener((View v, boolean hasFocus) -> {
                if (!hasFocus) {
                    String outStorageNumberStr = outStorageNumber.getText().toString();
//                    检测当前仓位出库数量是否为空
                    if (!TextUtils.isEmpty(outStorageNumberStr)) {
                        //正则表达式校验输入框内容
                        if (RegexUtils.checkDecimal(outStorageNumberStr)) {
                            //检测输入数量是否超过当前仓位库存
                            if (OutStorageUtils.checkInventory(pickingOutStorageItem.getStock_qty(), outStorageNumberStr)) {
                                pickingOutStorageItem.setQty(outStorageNumberStr);
                                mActualSendNumber = calculatedTotal();
                                actualSendNumber.setText("".equals(mActualSendNumber) ? "" : (mActualSendNumber + mUnit));
                            } else {
                                Utils.middleToast(mContext, mContext.getResources().getString(R.string.activity_out_storage_allocating_detail_exceed_current_position_inventory));
                                outStorageNumber.setText("");
                                pickingOutStorageItem.setQty("");
                                mActualSendNumber = calculatedTotal();
                                actualSendNumber.setText("".equals(mActualSendNumber) ? "" : (mActualSendNumber + mUnit));
                            }
                        } else {
//                            Utils.middleToast(mContext, "输入内容不合法");
//                            outStorageNumber.setText("");
                            pickingOutStorageItem.setQty("");
                            mActualSendNumber = calculatedTotal();
                            actualSendNumber.setText("".equals(mActualSendNumber) ? "" : (mActualSendNumber + mUnit));
                        }
                    } else {
                        pickingOutStorageItem.setQty("");
                        mActualSendNumber = calculatedTotal();
                        actualSendNumber.setText("".equals(mActualSendNumber) ? "" : (mActualSendNumber + mUnit));
                    }
                }
            });
            outStorageNumber.setText(pickingOutStorageItem.getQty());
            if (FOCUS_BATCH.equals(mIsFocusBatch)) {
                outStorageNumber.setFocusable(false);
                outStorageNumber.setBackground(null);
            }
            convertView.setOnLongClickListener((View v) -> {
                DialogUtils.getConfirmDialog(mContext, mContext.getResources().getString(R.string.activity_out_storage_allocating_detail_determine_to_delete_the_position) + pickingOutStorageItem.getPosition_code() +
                        mContext.getResources().getString(R.string.activity_out_storage_allocating_detail_batch) + pickingOutStorageItem.getBatch() + mContext.getResources().getString(R.string.activity_out_storage_allocating_detail_the_row_project), new DialogUtils.ConfirmDialogListener() {
                    @Override
                    public void onConfirm(Dialog dialog) {
                        dialog.cancel();
                        removeItem(pickingOutStorageItem);
                        notifyDataSetChanged();
                    }
                }).show();
                return true;
            });
        }
        return convertView;
    }

    public void addBatchRequest(Context context, boolean isScanner, String scannerContent, String batchNumber) {
        if (TextUtils.isEmpty(scannerContent) && TextUtils.isEmpty(batchNumber)) {
            Utils.middleToast(mContext, mContext.getResources().getString(R.string.activity_out_storage_allocating_detail_the_content_should_not_be_empty));
            return;
        }
        mBatchNumber = batchNumber;
        batchNumberEditText.setText(batchNumber);
        /*暂时修改由于伊泰还没有具体仓位码*/
//        int index = checkPosition(mBatchList, batchNumber);
//        if (index != -1) {
//            notifyDataSetChanged();
//            mOutStorageSaleDetailListener.selectItem(index);
//        } else {
        if (FOCUS_BATCH.equals(mIsFocusBatch)) {
            Utils.middleToast(mContext, mContext.getResources().getString(R.string.activity_out_storage_allocating_detail_the_position_information_was_not_found));
        } else {
            AddBatchRequest.request(mContext, batchNumber, mMaterielId, mFactoryId, mInventoryAddressId, null, TypeEnum.OUT_STORAGE_OTHER, new GsonBeanListener<BatchBean>() {
                @Override
                public void onSuccess(BatchBean bean) {
                    List<BatchBean.BatchInfoBean> realBatchList = OutStorageUtils.filterBatch(mBatchList, bean.getBody());
                    int size = realBatchList.size();
                    if (size > 1) {
                        DialogUtils.getAddBatchDialogNew(mContext, realBatchList, new DialogUtils.AddBatchListenerNew() {
                            @Override
                            public void onSelect(Dialog dialog, BatchBean.BatchInfoBean bean) {
                                mBatchList.add(bean);
                                notifyDataSetChanged();
                            }
                        }).show();
                    } else if (size == 1) {
                        mBatchList.addAll(realBatchList);
                        notifyDataSetChanged();
                    } else if (size == 0) {
                        Utils.middleToast(mContext, mContext.getResources().getString(R.string.activity_out_storage_allocating_detail_the_position_has_been_added_or_undetected));
                    }
                }
            });
        }
//        }
    }

    //计算实发数量
    private String calculatedTotal() {
        double result = 0D;
        for (int i = 0; i < mBatchList.size(); i++) {
            BatchBean.BatchInfoBean batchItem = mBatchList.get(i);
            double actualSendNumberDou;
            if (TextUtils.isEmpty(batchItem.getQty())) {
                actualSendNumberDou = 0D;
            } else {
                actualSendNumberDou = Double.parseDouble(batchItem.getQty());
            }
//            }
            result = ArithUtils.add(result, actualSendNumberDou);
        }
        return result == 0D ? "" : String.valueOf(result);
    }

    private void removeItem(BatchBean.BatchInfoBean pickingOutStorageItem) {
        for (int i = 0; i < mBatchList.size(); i++) {
            BatchBean.BatchInfoBean batchItem = mBatchList.get(i);
            if (batchItem.getPosition_code().equals(pickingOutStorageItem.getPosition_code()) && batchItem.getBatch().equals(pickingOutStorageItem.getBatch())) {
                mBatchList.remove(batchItem);
                break;
            }
        }
    }

//    private List<OutStoragePickingBatchListBean.DataBean.BatchListBean> filter(List<OutStoragePickingBatchListBean.DataBean.BatchListBean> allData, List<OutStoragePickingBatchListBean.DataBean.BatchListBean> returnData) {
//        List<OutStoragePickingBatchListBean.DataBean.BatchListBean> repeatList = new ArrayList<>();
//        for (int i = 0; i < returnData.size(); i++) {
//            OutStoragePickingBatchListBean.DataBean.BatchListBean returnItem = returnData.get(i);
//            for (int j = 0; j < allData.size(); j++) {
//                OutStoragePickingBatchListBean.DataBean.BatchListBean allItem = allData.get(j);
//                if (allItem.getPosition().equals(returnItem.getPosition()) && allItem.getBatch().equals(returnItem.getBatch())) {
//                    repeatList.add(returnItem);
//                }
//            }
//        }
//        returnData.removeAll(repeatList);
//        return returnData;
//    }

//    private boolean checkInventory(String inventoryNumber, String number) {
//        double inventoryNumberDou = Double.parseDouble(inventoryNumber);
//        double numberDou = Double.parseDouble(number);
//        if (inventoryNumberDou >= numberDou) {
//            return true;
//        } else {
//            return false;
//        }
//    }

//    private int checkPosition(List<OutStoragePickingBatchListBean.DataBean.BatchListBean> batchList, String position) {
//        int result = -1;
//        for (int i = 0; i < batchList.size(); i++) {
//            OutStoragePickingBatchListBean.DataBean.BatchListBean batchItem = batchList.get(i);
//            if (batchItem.getPosition().equals(position)) {
//                batchItem.setIsConfirm(CONFIRM);
//                result = i + 1;
//            }
//        }
//        return result;
//    }
}
